﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;

using Jungle.Code.Utils;
using Jungle.Code.DAL;
using Jungle.Code.BLL;
using Jungle.Code.Core;
using Jungle.Blog;
using Jungle.Forum;

public partial class UserInfo : BaseUserModule
{
    SessionKeeper ts = new SessionKeeper();
    protected override void OnInit(EventArgs e)
    {
        try
        {
            btn_Update.PostBackUrl = Request.RawUrl;
            btn_AddVote.PostBackUrl = Request.RawUrl;
            ts.SessionId = Session.SessionID.ToString();
            ts.GetData();
            if (Request["uId"] == null)
            {
                UserInfoMenu.ActiveViewIndex = 1;
                LoadDDls();
                LoadData();
            }
            else
            {
                UserInfoMenu.ActiveViewIndex = 0;
                LoadUser();
            }
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }   
        base.OnInit(e);
    }
    // -------------------------------------------------------------------------------------
    protected void LoadDDls()
    {
        DataSet cds = UserManager.GetCountrys();
        ddl_country.Items.Clear();
        for (int i = 0; i < cds.Tables[0].Rows.Count; i++)
        {
            ddl_country.Items.Add(new ListItem(cds.Tables[0].Rows[i][1].ToString(), cds.Tables[0].Rows[i][0].ToString()));
        }
    }
    // -------------------------------------------------------------------------------------
    protected void LoadData()
    {
        if (ts.UserId != -1)
        {
            UserManager um = new UserManager();
            um.UserId = ts.UserId;
            um.GetById();

            tb_Name.Text = um.Name;
            //ddl_country.SelectedValue = um.Country;
            tb_City.Text = um.City;
            tb_UserSignature.Text = um.UserSignature;
            WebDateChooser1.Value = um.BirthDay;
            lb_Points.Text = um.Points.ToString();
            lb_Raiting.Text = um.ForumRatingExist().ToString();
            img_Point.ImageUrl = UrlHelper.GetSiteUrl() + "/App_Themes/Poker/img/money.png";
            tb_ICQ.Text = um.ICQ;
            img_Avatar.ImageUrl = um.Avatar;
            ms1.Userid = ts.UserId;
            Jungle.Forum.Messages m = new Messages();
            tb_CountAlerts.Text = m.GetCountAlerts(um.UserId).ToString();
        }

    }
    // -------------------------------------------------------------------------------------
    protected void AddVote(object sender, EventArgs e)
    {
        try
        {
            if (ts.UserId != -1 && ts.UserId != Convert.ToInt32(Request["uId"]))
            {
                UserManager um = new UserManager();
                um.Rating_UsTo = Convert.ToInt32(Request["uId"]);
                um.Rating_UsWho = ts.UserId;
                um.Rating_UsRate = Convert.ToInt32(ddl_Votes.SelectedValue);
                um.Rating_Comment = tb_VoteComment.Text.Trim();

                    if (um.Rating_UsRate != 0)
                    {
                        um.AddRating();
                    }
                    else
                        tb_VoteComment.Text = "Укажите оценку!";
                
                LoadUser();

            }
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }
    }
    // -------------------------------------------------------------------------------------
    protected void LoadUser()
    {
        ddl_Votes.Items.Clear();
        for (int i = -10; i < 11; i++)
        {
            if(i == 0)
                ddl_Votes.Items.Add(new ListItem("Оценка", i.ToString()));
            else
            ddl_Votes.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        ddl_Votes.Items[10].Selected = true;

        UserManager user = new UserManager();
        user.UserId = Convert.ToInt32(Request["uId"]);
        user.GetById();

        user.Rating_UsTo = user.UserId;
        user.Rating_UsWho = ts.UserId;
        if (user.UserId == ts.UserId || ts.UserId == -1) div_AddVote.Visible = false;

        Post p = new Post();
        p.UserId = user.UserId;
        lb_CountPosts.Text = "Постов в блоге: " + p.GetCountPosts().ToString();
        lb_UserPoints.Text = "Очков: " + user.Points.ToString();
        lb_UserRaiting.Text = "Рейтинг: ";
        int raiting = user.ForumRatingExist();
        string span = "<span style=\"color: #A00;\">";
        if(raiting >= 0) span = span.Replace("#A00","#0A0");

        lb_UserRaiting.Text += span + Convert.ToInt32(raiting) + "</span>";
        lb_Title.Text = "Профиль пользователя " + user.NickName;
        img_UserAvatar.ImageUrl = UrlHelper.GetSiteUrl() + user.Avatar.Substring(1);
        if (user.ICQ.Length >= 5) lb_UserContacts.Text = "ICQ: " + user.ICQ + "<br/>";
        lb_UserInfo.Text = "<b>Зарегистрирован:</b> " + user.RegDate + "<br/>";
        lb_UserInfo.Text += "<b>День рождения:</b> " + user.BirthDay.ToShortDateString() + "<br/>";
        lb_UserInfo.Text += "<b>От куда:</b> " + user.City + "<br/><br/>";
        hp_toBlog.NavigateUrl = UrlHelper.GetSiteUrl() + "/blog/" + user.NickName + "/";
        hp_toRss.NavigateUrl = UrlHelper.GetSiteUrl() + "/admin/rss.aspx?s=blog&user=" + user.UserId.ToString();
        VotesList1.Ts = user.UserId;

        if (ts.UserId != -1)
        {
            hp_SendMessage.Text = "[Отправить сообщение]";
            hp_SendMessage.NavigateUrl = UrlHelper.GetSiteUrl() + "/ru/forum.aspx?mailbox=new&from=" + user.NickName;
        }
    }
    // -------------------------------------------------------------------------------------
    protected void AddAvatar(object sender, EventArgs e)
    {
        try
        {
            if (fu_Avatar.HasFile)
            {
                UserManager um = new UserManager();
                um.UserId = ts.UserId;
                um.GetById();

                System.Drawing.Image loadedImg = System.Drawing.Image.FromStream(fu_Avatar.PostedFile.InputStream);
                int height = 0;
                if (loadedImg.Height < 100)
                    height = loadedImg.Height;
                else
                    height = 100;
                int width = loadedImg.Width / (loadedImg.Height / height);

                System.Drawing.Image savedImg = loadedImg.GetThumbnailImage(width, height, null, IntPtr.Zero);

                string fname = "/UserFiles/Images/Avatars/" + Session.SessionID + "_" + um.NickName + ".jpg";
                if (um.Avatar.IndexOf("def.jpg") == -1)
                {
                    System.IO.File.Delete(Server.MapPath(um.Avatar.Substring(1)));
                }
                savedImg.Save(Server.MapPath(fname), System.Drawing.Imaging.ImageFormat.Jpeg);

                um.Avatar = "~" + fname;
                um.Update();
                LoadData();
            }
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }
    }
    // -------------------------------------------------------------------------------------
    protected void Update(object sender, EventArgs e)
    {
        try
        {
            UserManager um = new UserManager();
            um.UserId = ts.UserId;
            um.GetById();

            um.Name = tb_Name.Text.Trim();
            um.City = tb_City.Text;
            um.Country = Convert.ToInt32(ddl_country.SelectedValue);
            um.BirthDay = Convert.ToDateTime(WebDateChooser1.Value);
            um.ICQ = tb_ICQ.Text.Trim();
            um.UserSignature = tb_UserSignature.Text.Trim();
            if (UserManager.getMd5Hash(tb_OldPass.Text.Trim()) == um.Password)
                um.Password = UserManager.getMd5Hash(tb_NewPass.Text.Trim());
            um.Update();


            if (tb_CountAlerts.Text.Trim().Length == 0) tb_CountAlerts.Text = "0";
            Jungle.Forum.Messages m = new Messages();
            m.UpdateMO(um.UserId, Convert.ToInt32(tb_CountAlerts.Text.Trim()), 0);
        }
        catch (Exception ex)
        {
            GenerateEx(ex);
        }
    }
    // -------------------------------------------------------------------------------------
    protected void GenerateEx(Exception ex)
    {
        Response.Write("<div onclick=\"this.style.display='none';\" class=\"div_err\">Произошла ошибка. <br/> Данне о ней были переданы разработчикам. <br/> Приносим наши извенения за предоставленные неудобства.</div>");
        UserManager.SendEmail("t3.s@meta.ua", "Отчет по ошибке pokerminds.net", ex.Message.ToString() + "\r\n\r\n" + ex.StackTrace.ToString() + "\r\n\r\n" + ex.Source.ToString());
        UserManager.SendEmail("akobrinets@gmail.com", "Отчет по ошибке pokerminds.net", ex.Message.ToString() + "\r\n\r\n" + ex.StackTrace.ToString() + "\r\n\r\n" + ex.Source.ToString());
    }
}
